package cn.ekuma.odbo.mobile.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import timber.log.Timber

abstract class AbstractEntityAdapter<T,VH:View>(context: Context, entityList:List<T> = mutableListOf(), var layoutId:Int, var nullAble: Boolean =false, var allAble: Boolean =false) : ArrayAdapter<T>(context, layoutId,entityList) {

    var systemCount=0

    init {
        if(nullAble) systemCount++
        if(allAble) systemCount++
    }

    override fun getItem(position: Int): T? {
        if(position<systemCount)
            return null
        return super.getItem(getRealPosition(position))
    }

    /*override fun getItemId(position: Int): Long {
        val realPostion=getRealPosition(position)
        return super.getItemId(realPostion)
    }*/

    override fun getCount(): Int {
        return systemCount+super.getCount()
    }

    override fun getPosition(item: T?): Int {
        return systemCount+super.getPosition(item)
    }

    override fun insert(`object`: T?, index: Int) {
        super.insert(`object`, getRealPosition(index))
    }

    protected val mInflater = LayoutInflater.from(context)!!

    override fun getView(position: Int, convertView: View?,parent: ViewGroup): View {
        return createPositionView(mInflater, position, convertView, parent)
    }

    fun isNullSelected(position: Int): Boolean = nullAble&&position==0

    fun isAllSelected(position: Int): Boolean = allAble&&nullAble&&position==1||allAble&&position==0

    protected fun getRealPosition(position: Int):Int=position-systemCount

    abstract fun displayItemToTextView(view: VH, item:T?, position: Int)

    abstract fun displaySystemToView(view: VH, position: Int)

    fun createPositionView(inflater: LayoutInflater,position: Int, convertView: View?,parent: ViewGroup):VH {
        //Timber.d("entity adapter get view at:$position item Count:${getCount()} \t systemCount:$systemCount")
        var view: VH = if(convertView!=null)
            convertView as VH
        else
            inflater.inflate( layoutId, parent, false) as VH
        if (position < systemCount) {
            displaySystemToView(view, position)
        } else {
            val item = getItem(position)
            displayItemToTextView(view,item,position)
        }
        return view
    }

    override fun getDropDownView(position: Int, convertView: View?,parent: ViewGroup): View? {
        return createPositionView(mInflater, position, convertView, parent)
    }
}